/* eslint-disable */
import store from './store'
import {Message} from 'element-ui'
import router, { constantRoutes, resetRouter } from '@/router'
import NProgress from 'nprogress' // progress bar   加载进度条
import 'nprogress/nprogress.css'
NProgress.configure({showSpinner: false})
import {getToken} from '@/utils/auth'
const whiteList = ['/register', '/login' ,'/forget']


router.beforeEach(async (to, from, next) => {

    NProgress.start()
    const hasToken = getToken()
    if (hasToken) {
        // 如果当前状态为登陆状态，手动输入login直接跳转去首页
        if (to.path === '/login') {
            next({path: '/'})
            NProgress.done()
        } else {
            try {
                // 获取用户信息->根据用户信息获取对应权限->渲染路由并进入平台
                if ( !store.getters.userInfo.remark ){
                    const needRoutes = await store.dispatch('user/getInfo')
                    resetRouter() // 重置路由结构(避免动态添加重复路由问题)
                    router.addRoutes(needRoutes); // 动态添加路由
                    next({ ...to, replace: true })
                }else {
                    next()
                }
            }catch (e) {
                next(`/login`)
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})


router.afterEach(() => {
    NProgress.done()
})
